package com.base.springboot.starter.common.http;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * httpclient 工厂类
 * User: wangwei
 * Date: 2021-05-20 6:42 下午
 */
public class CsHttpClientRepo {

    public static final int MAX_NUM = 30;

    private volatile ConcurrentHashMap<String, CaissaHttpClient> container = new ConcurrentHashMap<>();

    @Autowired
    private PoolingHttpClientConnectionManagerMonitor poolingHttpClientConnectionManagerMonitor;

    /**
     * 创建或获取已有的 CsHttpClient 实例，默认参数
     * @param name
     * @return
     */
    public CaissaHttpClient createOrGet(String name){
        return createOrGet(name, null);
    }

    /**
     * 创建或获取已有的 CsHttpClient 实例，指定参数
     * @param name
     * @param config
     * @return
     */
    public CaissaHttpClient createOrGet(String name, CsHttpClientConfig config) {

        Objects.requireNonNull(name);

        if (container.size() > MAX_NUM) {
            throw new IllegalStateException("httpclient 实例数超过 " + MAX_NUM);
        }

        CaissaHttpClient csHttpClient = container.get(name);

        if (csHttpClient != null) {
            return csHttpClient;
        }

        synchronized (CsHttpClientRepo.class) {
            csHttpClient = container.putIfAbsent(name, new CaissaHttpClient(name, config));
            if (csHttpClient == null) {
                csHttpClient = container.get(name);
                poolingHttpClientConnectionManagerMonitor.addPoolingHttpClientConnectionManager(name, csHttpClient.getConnectionManager());
                csHttpClient.preHeat();
            }
        }

        return csHttpClient;
    }
}
